<template>
  <PrivacyPopup></PrivacyPopup>
  <PageLayout full :page-style="pageStyle">
    <!--头部导航-->
    <template #header>
      <HeaderLayout show-back>
        <view>账号设置</view>
      </HeaderLayout>
    </template>
    <!--内容-->
    <view class="container">
      <!--头像-->
      <view class="head-cell">
        <view class="set-text">头像</view>
        <view class="head">
          <button class="photo" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
            <image class="header-image" mode="widthFix" :src="avatarUrl" v-if="avatarUrl"></image>
            <image class="header-image" mode="widthFix" src="/static/ic_header.png" v-if="!avatarUrl"></image>
          </button>
          <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
        </view>
      </view>
      <!--分割线-->
      <view class="line"></view>
      <!--昵称-->
      <view class="nick-cell" @click="changeNickName">
        <view class="set-text">昵称</view>
        <view class="nick">
          <view class="user-name">{{ userName }}</view>
          <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
        </view>
      </view>
      <!--账号管理-->
      <view class="general-cell" @click="goToAccountManager()">
        <view class="set-text">账号管理</view>
        <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
      </view>
      <!--退出登录-->
      <view class="general-cell" @click="loginOut">
        <view class="set-text">{{ $t('My.AccountSetting.LoginOut.Button.Text') }}</view>
        <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
      </view>
    </view>

    <!-- 修改昵称弹窗 -->
    <Modal
      v-if="changeNicknameFlag"
      :title="'昵称'"
      :visible="changeNicknameFlag"
      :cancel-text="$t('APP.Common.Cancel.Text')"
      :ok-text="$t('APP.Common.Confirm.Text')"
      :ok-disabled="isErrorName"
      @ok="confirmChange"
      @cancel="cancel"
      :bottom-offset="inputBottom"
    >
      <view class="tip">
        <view class="input-container">
          <input
            @input="inputTextChange"
            class="tip-input"
            type="text"
            v-model="newUserName"
            placeholder="请输入用户名"
            minlength="2"
            maxlength="32"
            :focus="tempFocus"
            @keyboardheightchange="keyboardheightchange"
            @blur="blur"
          />
        </view>
        <view class="tip-text">2-32个字符长度，仅支持中英文</view>
      </view>
    </Modal>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import Modal from '@/common/modal.vue'

import { onLoad, onShow } from '@dcloudio/uni-app'
import { goBackPage } from '@/utils/mpHelper'

import { useAuthStore } from '@/store/auth'
import { getWxDetail } from '@/api/account'
import { changeNickname } from '@/api/account'
import { clearApplianceCache } from '@/controller/base/cacheHelper'
import { actionDebounce } from '@/utils/mpHelper'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import PrivacyPopup from '@/pages/navigator/components/privacyPopup.vue'

const authStore = useAuthStore()

const pageStyle = {
  backgroundColor: '#F4F4F4',
}

let nav = false

const tempFocus = ref(true)
const changeNicknameFlag = ref(false)
const userName = ref('')
const newUserName = ref('')
const avatarUrl = ref('')
const getProfile = ref(false)

onLoad((options) => {
  getProfile.value = options?.getProfile
  avatarUrl.value = options?.getProfile ? options?.avatarUrl : ''
  userName.value = options?.userName
  checkUserName(newUserName.value)
})

onShow(() => {
  getUserInfo()
  if (authStore.isLogin) {
    getWxDetailFun()
  }
})

function getUserInfo() {
  let userProfile = uni.getStorageSync('userProfile')
  if (userProfile && userProfile.userName) {
    userName.value = userProfile.userName
    avatarUrl.value = userProfile.avatarUrl
  } else {
    userName.value = ''
    avatarUrl.value = ''
  }
}
/**
 * 获取用户信息和未读信息
 */
async function getWxDetailFun() {
  try {
    const res = await getWxDetail()
    userName.value = res.data.lastname + res.data.firstname
    uni.setStorage({
      key: 'userProfile',
      data: { userName: userName.value, avatarUrl: avatarUrl.value },
    })
  } catch (error) {
    console.error('获取用户信息失败：', error)
  }
}
/**
 * 退出登录
 */
function loginOut() {
  trackEvent('quit_account', {}, TrackType.ApplianceDetail, 'My.AccountSetting.LoginOut.Button.Text')
  if (nav) {
    uni.showToast({
      title: '操作太快，请稍候',
      icon: 'none',
    })
    return
  }
  nav = true
  authStore.removeAllUserInfo()
  avatarUrl.value = ''

  // 移除家电缓存
  clearApplianceCache()

  goBackPage()
  setTimeout(() => {
    nav = false
  }, 1500)
}

/**
 * 选择头像
 * @param e
 */
function onChooseAvatar(e: WechatMiniprogram.CustomEvent<{ avatarUrl: string }>) {
  avatarUrl.value = e.detail.avatarUrl
  const oldProfile = uni.getStorageSync('userProfile')
  const newProfile = {
    ...oldProfile,
    ...(userName.value && { nickName: userName.value }),
    ...(avatarUrl.value && { avatarUrl: avatarUrl.value }),
  }
  // console.error(newProfile)
  trackEvent(
    'modify_account',
    { avatar_is_modified: true, username_is_modified: false },
    TrackType.BusinesssScene,
    'My.AccountSetting.Header.Setting'
  )

  uni.setStorageSync('userProfile', newProfile)
}

/**
 * 跳转到账号管理
 */
function goToAccountManager() {
  uni.navigateTo({
    url: '/pages/my/accountManager/accountManager',
  })
}

/**
 * 点击昵称cell
 */
function changeNickName() {
  newUserName.value = userName.value
  changeNicknameFlag.value = true
  nextTick(() => (tempFocus.value = true))
}

/**
 * 弹窗 取消
 */
function cancel() {
  changeNicknameFlag.value = false
}

/**
 * 重新输入账号名
 * @param e
 */
function inputTextChange(e: Event) {
  let name = (e as unknown as WechatMiniprogram.Input).detail.value
  checkUserName(name)
}

/**
 * 确定修改昵称
 */
const confirmChange = actionDebounce({
  delay: 300,
  showLoading: true,
  call: async () => {
    trackEvent(
      'before_modify_account',
      { avatar_is_modified: false, username_is_modified: true },
      TrackType.BusinesssScene,
      'My.AccountSetting.NickName.Setting'
    )
    if (isErrorName.value) return
    return changeNickname(newUserName.value)
  },
  then: (res) => {
    if (!res) return

    uni.showToast({
      title: '修改成功',
    })
    userName.value = newUserName.value
    authStore.updateToken(res.data)
    trackEvent(
      'modify_account',
      {
        avatar_is_modified: false,
        username_is_modified: true,
        successOrNot: res.code == 0,
        error_code: res.code,
        response_msg: res.msg,
      },
      TrackType.BusinesssScene,
      'My.AccountSetting.NickName.Setting'
    )
  },
  catch: (error) => {
    console.error('重命名失败：', error)
    trackEvent(
      'modify_account',
      {
        avatar_is_modified: false,
        username_is_modified: true,
        successOrNot: false,
        error_code: error.code,
        response_msg: error.msg,
      },
      TrackType.BusinesssScene,
      'My.AccountSetting.NickName.Setting'
    )
  },
  finally: () => {
    changeNicknameFlag.value = false
  },
})

/**
 * 用户名校验
 * @param name 用户名
 */
const isErrorName = ref(false) //true:命名错误 false:命名正确
function checkUserName(name: string) {
  let pattern = /^[a-zA-Z\u4e00-\u9fa5]{2,32}$/
  if (pattern.test(name)) {
    isErrorName.value = false
  } else {
    isErrorName.value = true
  }
}
/**
 * 键盘高度发生变化的时候触发此事件
 */
const inputBottom = ref('')
function keyboardheightchange(e: WechatMiniprogram.InputKeyboardHeightChange) {
  let height = e.detail.height + 'rpx'
  inputBottom.value = height
}
/**
 * 输入框失去焦点时触发，event.detail = {value: value}
 */
function blur() {
  tempFocus.value = false
}
</script>

<style lang="less">
// 设置
.container {
  margin-top: 16rpx;
  .head-cell {
    background-color: #fff;
    padding: 0 32rpx;
    height: 148rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .head {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 148rpx;
      .photo {
        margin: 0;
        padding: 0;
        margin-right: 24rpx;
        width: 88rpx;
        height: 88rpx;
        border-radius: 50%;
        overflow: hidden;
        .header-image {
          width: 88rpx;
          height: 88rpx;
          border-radius: 40rpx;
        }
      }
      .photo:after {
        border: none;
      }
    }
  }
  // 分割线
  .line {
    height: 1rpx;
    background-color: #e2e2e2;
    margin: 0rpx 32rpx;
  }
  // 昵称
  .nick-cell {
    height: 88rpx;
    background-color: #fff;
    padding: 0 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8rpx;
    .nick {
      display: flex;
      align-items: center;
      justify-content: space;
      .user-name {
        font-size: 30rpx;
        color: #2d3746;
        opacity: 0.6;
        margin-right: 24rpx;
      }
    }
  }

  .general-cell {
    height: 88rpx;
    background-color: #fff;
    padding: 0 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16rpx;
  }
}
// 箭头
.arrow-right {
  width: 16rpx;
  height: 28rpx;
}

.photo-box {
  width: 100%;
  height: 100%;
  background-color: green;
}

.set-text {
  margin-left: 10rpx;
  font-weight: 500;
  font-size: 32rpx;
  color: var(--dark-color);
  opacity: 0.9;
}

.updateView {
  font-family: PingFangSC-Regular;
  font-size: 32rpx;
  color: #131b35;
  text-align: center;
  line-height: 50rpx;
  font-weight: 400;
  padding: 0 40rpx 60rpx;
}

.tip {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: left;
  .tip-text {
    color: var(--primary-color);
    font-size: 24rpxrpx;
    text-align: left;
    padding-top: 16rpx;
  }
  .tip-input {
    text-align: left;
    height: 80rpx;
    margin: auto 16rpx;
  }
  .input-container {
    background-color: rgb(228, 227, 233);
    height: 80rpx;
    border-radius: 8rpx;
  }
}
</style>
